package org.dx.oho.book.one.proxy.cglib;


import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * create by duanx 2021/5/24
 *@description： todo
 *@classname: CglibProxyExample
 *@author: duanx
 *@date: 2021/5/24 22:43
 **/
public class CglibProxyExample implements MethodInterceptor {

    private static Logger logger = LoggerFactory.getLogger(CglibProxyExample.class);

    /**
     * 生成Cglib代理对象
     * @param clazz 代理目标对象类
     * @return 代理目标的Cglib代理对象
     */
    public Object getProxy(Class<?> clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        logger.info("为"+clazz.getName()+"创建代理对象");
        return enhancer.create();
    }

    /**
     * 代理的逻辑
     * @param o 代理目标
     * @param method 方法
     * @param objects 参数
     * @param methodProxy 方法代理
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, @NotNull MethodProxy methodProxy) throws Throwable {
        logger.info("调用真实对象之前");
        Object result = methodProxy.invokeSuper(o,objects);
        logger.info("调用真实对象之后");
        return result;
    }

}
